package com.mediacloud.app.newsmodule.fragment.imagetext;

import android.annotation.SuppressLint;
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.widget.NestedScrollView;

public class CustomScrollView extends NestedScrollView {
    private onScrollOverListener mListener;
    /**
     * 手指是否抬起
     */
    private boolean isFingerUp = true;
    /**
     * 是否正在滑动
     */
    public boolean isScrolling = false;

    private final long mDragDelayTime = 100;

    /**
     * 100毫秒后发送滚动结束的指令，若继续有滚动事件，则取消发送
     */
    private Thread mDragThread = new Thread(new Runnable() {
        @Override
        public void run() {
            if (mListener != null) {
                if (isFingerUp) {
                    mListener.scrollOver(true);
                }
                isScrolling = false;
            }
        }
    });

    @Override
    protected void onScrollChanged(int x, int y, int oldx, int oldy) {
        super.onScrollChanged(x, y, oldx, oldy);
        if (mListener != null) {
            //100毫秒后发送滚动结束的指令，若继续有滚动事件，则取消发送
            isScrolling = true;
            removeCallbacks(mDragThread);
            mListener.scrollOver(false);
            postDelayed(mDragThread, mDragDelayTime);
        }
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_UP) {
            isFingerUp = true;
            if (!isScrolling && mListener != null) {
                mListener.scrollOver(true);
            }
        } else if (ev.getAction() == MotionEvent.ACTION_MOVE) {
            isFingerUp = false;
        }
        return super.onTouchEvent(ev);
    }

    public CustomScrollView(@NonNull Context context) {
        this(context, null);
    }

    public CustomScrollView(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CustomScrollView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onOverScrolled(int scrollX, int scrollY, boolean clampedX, boolean clampedY) {
        super.onOverScrolled(scrollX, scrollY, clampedX, clampedY);
    }

    public void setScrollOverListener(onScrollOverListener mListener) {
        this.mListener = mListener;
    }

    public interface onScrollOverListener {
        void scrollOver(boolean overScroll);
    }
}